package rs.dalao.syc.passport.controller;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import rs.dalao.syc.common.pojo.authentication.CurrentPrincipal;
import rs.dalao.syc.common.response.JsonResult;
import rs.dalao.syc.common.response.ServiceCode;
import rs.dalao.syc.passport.pojo.param.DoctorRegParam;
import rs.dalao.syc.passport.pojo.param.UserLoginInfoParam;
import rs.dalao.syc.passport.pojo.param.UserRegParam;
import rs.dalao.syc.passport.pojo.vo.UserLoginResultVO;
import rs.dalao.syc.passport.service.IUserService;
import rs.dalao.syc.passport.service.Impl.UserServiceImpl;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/passport/")
public class UserController {
    @Autowired
    private IUserService userService;

    //用户注册
    @PostMapping("users/reg")
    @ApiOperation("用户注册")
    public JsonResult userReg(UserRegParam userRegDTO){
        userService.userReg(userRegDTO);
        return JsonResult.ok();
    }

    //获取验证码
    @PostMapping("users/getCode/{phone}")
    @ApiOperation("获取验证码")
    public JsonResult getCode(@PathVariable String phone){
        Integer code = userService.getCode(phone);
        if(code==-1){
            String message ="验证码发送失败！";
            return JsonResult.fail(ServiceCode.ERR_CODE_SEND,message);
        }
        return JsonResult.ok();
    }

    //用户登录
    @PostMapping("users/login")
    @ApiOperation("用户登录")
    public JsonResult login(UserLoginInfoParam userLoginInfoParam,
                            @ApiIgnore HttpServletRequest request){
        log.debug("开始处理【用户登录】的请求，参数：{}",userLoginInfoParam);

        String remoteAddr = request.getRemoteAddr();//ip地址
        String userAgent = request.getHeader("User-Agent");//浏览器信息
        System.out.println("ip="+remoteAddr);
        System.out.println("浏览器信息："+userAgent);

        UserLoginResultVO loginResult = userService.login(userLoginInfoParam,remoteAddr,userAgent);
        return JsonResult.ok(loginResult);
    }

    @PostMapping("users/logout")
    @ApiOperation("用户退出")
    public JsonResult logout(@AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal){
        userService.logout(currentPrincipal);
        return JsonResult.ok();
    }

    @PostMapping("doctors/reg")
    @ApiOperation("医生注册")
    public JsonResult doctorReg(DoctorRegParam doctorRegParam){
        userService.doctorReg(doctorRegParam);
        return JsonResult.ok();
    }

}
